#    Copyright (C) 2003-2008 William Waites
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Support for use of BGP updates data from http://www.routeviews.org/
"""

from adjacencies.graph import Path
from pybgpdump import BGPDump
from dpkt import bgp

__all__ = ['load_updates']

def load_updates(fname, mesh, radix=None):
	"""
	Load updates from the given file into the provided mesh. The mesh
	is expected to be an instance of adjacencies.graph.Mesh. If an 
	optional radix key word argument is supplied, the announced routes
	are added to the appropriate origin AS(s) and entered into the 
	radix tree. Likewise if routes are withdrawn they are removed from
	the appropriate AS(s)
	"""
	for mrt_h, bgp_h, bgp_m in BGPDump(fname):
		for attr in bgp_m.update.attributes:
			if attr.type == bgp.AS_PATH:
				path = Path(attr.as_path)
				mesh.add_path(Path(attr.as_path))
		if radix and bgp_m.update.announced:
			for route in bgp_m.update.announced:
				rnode = radix.add(packed=route.prefix, masklen=route.len)
				paths = rnode.data.setdefault("paths", {})
				paths[path] = None
				origin_as = path[-1]
				if not isinstance(origin_as, list):
					origin_as = [origin_as]
				for asn in origin_as:
					asn.announce((rnode.network, rnode.prefixlen))
		if radix and bgp_m.update.withdrawn:
			for route in bgp_m.update.withdrawn:
				rnode = radix.search_exact(packed=route.prefix, masklen=route.len)
				if not rnode:
					continue
				for path in rnode.data.get("paths", []):
					origin_as = path[-1]
					if not isinstance(origin_as, list):
						origin_as = [origin_as]
					for asn in origin_as:
						asn.withdraw((rnode.network, rnode.prefixlen))	
